#region

using Microsoft.AspNetCore.Mvc;
using Vin.AspNetCore.Core.Controller;
using Vin.Extension.Framework.Geo.Entities;
using Vin.Extension.Framework.Geo.Repository;
using Vin.Tool.AspNetCore.Filter;
using Vin.Tool.Core.JsonCategory;

#endregion

namespace Vin.Framework.Api.Tests.Controllers;

public class TestSmsController : VinBaseController
{
    private SysGeoRepository _sysGeoRepository;

    private List<SysGeo> allList;

    public TestSmsController(SysGeoRepository sysGeoRepository)
    {
        _sysGeoRepository = sysGeoRepository;
        allList = _sysGeoRepository.GetList();
    }

    private async Task ChangeDeepName(List<SysGeo> geoList)
    {
        foreach (var geo in geoList)
        {
            if (geo.Deep == 0)
            {
                // 省级
                geo.DeepName = geo.FullName;
            }

            if (geo.Deep == 1)
            {
                // 市级
                var parent = allList.FirstOrDefault(m => m.Id == geo.Pid);
                geo.DeepName = $"{parent?.FullName}-{geo.FullName}";
            }

            if (geo.Deep == 2)
            {
                // 区级
                var parent = allList.FirstOrDefault(m => m.Id == geo.Pid);
                var parentParent = allList.FirstOrDefault(m => m.Id == parent?.Pid);
                geo.DeepName = $"{parentParent?.FullName}-{parent?.FullName}-{geo.FullName}";
            }

            if (geo.Deep == 3)
            {
                // 街道
                var parent = allList.FirstOrDefault(m => m.Id == geo.Pid);
                var parentParent = allList.FirstOrDefault(m => m.Id == parent?.Pid);
                var parentParentParent = allList.FirstOrDefault(m => m.Id == parentParent?.Pid);
                geo.DeepName =
                    $"{parentParentParent?.FullName}-{parentParent?.FullName}-{parent?.FullName}-{geo.FullName}";
            }
        }

        await _sysGeoRepository.Context.Fastest<SysGeo>()
            .BulkUpdateAsync(geoList, new[] { "id" }, new[] { "deep_name" });
    }

    [HttpGet("/send")]
    public async Task<IActionResult> Send()
    {
        System.IO.File.WriteAllText("geo.json", allList.ToJson());

        await ChangeDeepName(allList.Where(m => string.IsNullOrEmpty(m.DeepName)).ToList());

        return Success();
    }

    [IpAuthActionFilter, HttpGet("/ip")]
    public IActionResult Ip()
    {
        return Success();
    }
}